import json
import os
import sys
import threading

import requests
from PyQt6.QtWidgets import QApplication

from scripts import video_parser, image_utils, db_utils
from app import server
from scripts.midjourney import midjourney
from global_config import *
from ui.dialogs.CommonPromptsDialog import CommonPromptsDialog


def generate_images():
    storyboards_path = get_storyboards_path()
    if os.path.exists(storyboards_path):
        storyboards = db_utils.read_workflow(storyboards_path)
        for i, bean in enumerate(storyboards):
            if bean.ref_img is not None:
                bean.ref_img = None
                print(bean.img_name, bean.ref_img)
        # 缓存分镜数据
        db_utils.save_wordflow(storyboards_path, storyboards)


def upload_returndata():
    with open(f'{root}\\scripts\\midjourney\\uploaddata.json', 'r') as file:
        pic_urls = json.load(file)
        storyboards_path = get_storyboards_path()
        if os.path.exists(storyboards_path):
            storyboards = db_utils.read_workflow(storyboards_path)
            print(pic_urls)
            for i, bean in enumerate(storyboards):
                for url in pic_urls:
                    if bean.trigger_id and bean.trigger_id in url:
                        bean.ref_img = url
                        print(bean.img_name, bean.ref_img)
                        break
            # 缓存分镜数据
            db_utils.save_wordflow(storyboards_path, storyboards)


def get_storyboards_path():
    workflow_path = f'{workflows_dir}asdf\\'
    storyboards_path = f'{workflow_path}{workflows_json}'
    if not os.path.exists(workflow_path):
        os.mkdir(workflow_path)
    return storyboards_path


def test2():
    storyboards_path = get_storyboards_path()

    # 根据字幕文件，提取出关键帧, 并生成分镜数据
    storyboards = video_parser.movie2Storyboard(get_video_path(), get_srt_path(), get_frames_path())
    # 缓存分镜数据
    db_utils.save_wordflow(storyboards_path, storyboards)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    confirm_dialog = CommonPromptsDialog(None)
    result = confirm_dialog.get_result()

    if result:
        print("用户选择了继续")
    else:
        print("用户取消了操作")

    sys.exit(app.exec())